package com.example.wowangz.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import redis.clients.jedis.JedisPoolConfig;

@Configuration
@EnableConfigurationProperties(RedisProperties.class)
@AutoConfigureBefore(RedisConfig.class)
public class RedisConfig {
	
	@Bean(name = { "RedisProperties" })
	@ConditionalOnMissingBean
	public RedisProperties redisProperties() {
		return new RedisProperties();
	}

	@Autowired
	@Qualifier("RedisProperties")
	private RedisProperties properties;

	@Bean
	public RedisConnectionFactory jedisConnectionFactory() {
		JedisPoolConfig poolConfig = new JedisPoolConfig();
		poolConfig.setMaxTotal(properties.getPool().getMaxActive());
		poolConfig.setMaxIdle(properties.getPool().getMaxIdle());
		poolConfig.setMaxWaitMillis(properties.getPool().getMaxWait());
		poolConfig.setMinIdle(properties.getPool().getMinIdle());
		poolConfig.setTestOnBorrow(true);
		poolConfig.setTestOnCreate(true);
		poolConfig.setTestWhileIdle(true);
		JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(poolConfig);
		jedisConnectionFactory.setHostName(properties.getHost());
		if (null != properties.getPassword()) {
			jedisConnectionFactory.setPassword(properties.getPassword());
		}
		jedisConnectionFactory.setPort(properties.getPort());

		// 其他配置，可再次扩展

		return jedisConnectionFactory;
	}

	@Bean(name = "redisTemplate")
	@ConditionalOnMissingBean(name = { "redisTemplate" })
	public RedisTemplate<String, String> redisTemplate() {
		RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
		redisTemplate.setConnectionFactory(jedisConnectionFactory());
		return redisTemplate;
	}
	
	@Bean(name = "stringRedisTemplate")
	public StringRedisTemplate stringRedisTemplate() {
		StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
		stringRedisTemplate.setConnectionFactory(jedisConnectionFactory());
		return stringRedisTemplate;
	}

}
